package com.jinxin.platform.cdfaceacs.controller;

import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdfaceacs.bean.CdqzsqacsDevice;
import com.jinxin.platform.cdfaceacs.bean.CdqzsqacsOpenRecord;
import com.jinxin.platform.cdfaceacs.bean.bo.RecordInfo;
import com.jinxin.platform.cdfaceacs.bean.bo.UserInfo2;
import com.jinxin.platform.cdfaceacs.bean.gaEntity.Ga_mjjcxx;
import com.jinxin.platform.cdfaceacs.common.Constant;
import com.jinxin.platform.cdfaceacs.mapper.CdqzsqacsDeviceMapper;
import com.jinxin.platform.cdfaceacs.mapper.CdqzsqacsOpenRecordMapper;
import com.jinxin.platform.cdfaceacs.rpc.SysUserRpc;
import com.jinxin.platform.cdfaceacs.utils.BizUtil;
import com.jinxin.platform.cdfaceacs.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-05-21
 * @Author: Lingnan
 **/
@RestController
@RequestMapping("/unAuth")
@Slf4j
public class QzsqUnauthController {
    @Autowired
    private CdqzsqacsOpenRecordMapper openRecordMapper;
    @Autowired
    private CdqzsqacsDeviceMapper deviceMapper;
    @Autowired
    private SysUserRpc sysUserRpc;

    @PostMapping("/api/downdata/saveUserInfo.html")
    public Map<String, Object> saveUserInfo( HttpServletRequest request ){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream(), StandardCharsets.UTF_8));
            StringBuffer sb = new StringBuffer("");
            String temp;
            while ((temp = br.readLine()) != null) {
                sb.append(temp);
            }
            br.close();
            String acceptjson = sb.toString();
            log.info("---------------智慧门禁上报:"+ acceptjson);
            String jsonNwe = JSONObject.parseObject(acceptjson).get("Recards").toString().replace("//","" );
            List<RecordInfo> infoDOS = JSONObject.parseArray(jsonNwe, RecordInfo.class );
            List<Ga_mjjcxx> mjjcxxList = new ArrayList<>();
            for (RecordInfo info: infoDOS){
                String devMAC = info.getDevMAC();
                String id = BizUtil.convMac216(devMAC)+ info.getId();
                CdqzsqacsOpenRecord selInfo = openRecordMapper.selectByKey(id);
                if(null == selInfo){
                    CdqzsqacsOpenRecord infoDO = new CdqzsqacsOpenRecord();
                    int ioType = info.getIOType();
                    String openType;
                    switch (ioType){
                        case 1: openType = "刷卡";break;
                        case 2: openType = "人脸识别";break;
                        case 3: openType = "视频对接";break;
                        case 4: openType = "网络";break;
                        case 5: openType = "按钮";break;
                        case 6: openType = "无线";break;
                        default: openType = "未知";break;
                    }
                    infoDO.setOpenType(openType);
                    infoDO.setId(id);
                    long ioTime = info.getIOTime();
                    LocalDateTime openTime = DateUtil.getDateTimeOfTimestamp(ioTime * 1000);
                    infoDO.setOpenTime(openTime);
                    String userID = info.getUserID()+"";
                    infoDO.setOpenUserId(userID +"");
                    HashMap param = new HashMap();
                    param.put("deviceMac",devMAC.toLowerCase());//这里是大写的需要转成小写
                    CdqzsqacsDevice device = deviceMapper.selectOne(param);
                    StringBuffer fkSource = new StringBuffer();
                    String serialNum = "",communityId = "";
                    if(device != null){
                        serialNum = device.getSerialNum();
                        infoDO.setSerialNum(serialNum);
                        communityId = device.getCommunityId();
                        infoDO.setCommunityId(communityId);
                        String communityName = device.getCommunityName();
                        infoDO.setCommunityName(communityName);
                        infoDO.setDeviceName(device.getDeviceName());
                        fkSource.append(communityName);
                    }
                    // 通过userId查询用户信息
                    UserInfo2 userInfo = sysUserRpc.getUserInfoById(userID);
                    String userName = "",cardNo = "";
                    if(userInfo != null){
                        userName = userInfo.getUserName();
                        cardNo = userInfo.getUserCard();
                        infoDO.setOpenUser(userName);
                        infoDO.setCardNo(cardNo);
                        infoDO.setPhone(userInfo.getUserPhone());
                        String personType = "未知";
                        String userType = userInfo.getUserType();
                        if(!StringUtils.isEmpty(userType)){
                            switch (userType){
                                case "11":personType = "业主";break;
                                case "12":personType = "家庭成员";break;
                                case "13":personType = "租客";break;
                                case "14":personType = "其他";break;
                                default:personType = "未知";break;
                            }
                        }
                        infoDO.setPersonType(personType);
                        fkSource.append(userInfo.getUserBlockName());
                        fkSource.append(userInfo.getUserUnitName());
                        fkSource.append(userInfo.getUserRoomName());
                    }
                    infoDO.setSource(fkSource.toString());
                    String cjsj = (int) (System.currentTimeMillis() / 1000) + "";
                    Ga_mjjcxx cjsbxx = Ga_mjjcxx.builder().MJJCJLXXBZ(id).XM(userName)
                            .GMSFZHM(cardNo).PZH("").MJDBH("").SK_RQSJ(openTime.toString())
                            .MCZT("1").GLDMJ_CJSBXXBZ(serialNum).SFTG_PDBZ("1").KMFSDM("4").KMJG("1")
                            .MJSJLX("0").CJSJ(cjsj).XQXXBZ("noTimeFormatRequired@"+communityId).SJLY(Constant.DEVICE_SYLY).OPERATE_TYPE("add").build();
                    mjjcxxList.add(cjsbxx);
                    openRecordMapper.insert(infoDO);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("status",1);
        resMap.put("msg","请求成功");
        resMap.put("uninsert", new ArrayList<>() );
        return resMap;
    }
}
